<template>
  <div class="dashboard-container">
    <div class="app-container">
      <Headline title-name="员工" />
      <PageTools :show-before="true">
        <template slot="before">
          <el-alert
            :title="'本公司一共有'+total+'个员工'"
            type="info"
            show-icon
          />
        </template>
        <template slot="after">
          <el-button type="primary" icon="el-icon-download" @click="$router.push('/import?type=employee')">导入</el-button>
          <el-button type="primary" icon="el-icon-upload2" @click="exportData">导出</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="addDialog">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <el-table
          :data="employeesList"
          stripe
          style="width: 100%"
        >
          <el-table-column label="序号" width="180" :sortable="true">
            <template slot-scope="{$index}">
              {{ (pageSetting.page-1) * pageSetting.size +1 +$index }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" :sortable="true" prop="username" />
          <el-table-column label="工号" :sortable="true" prop="workNumber" width="80" />
          <el-table-column label="头像" prop="staffPhoto" align="center">
            <template slot-scope="{row}">
              <img v-imgerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto" style="border-radius:50%;width:100px;height:100px;object-fit:cover;" @click="showCodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="聘用形式" :sortable="true" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" :sortable="true" prop="departmentName" />
          <el-table-column label="入职时间" :sortable="true">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" :sortable="true">
            <template slot-scope="{row}">
              <el-switch
                :value="row.enableState === 1"
                disabled
              />

            </template>
          </el-table-column>
          <el-table-column label="操作" :sortable="true" prop="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button v-if="checkPermission('point-user-delete')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="end" align="center" style="height:60px">
          <el-pagination
            layout="prev, pager, next,sizes,total"
            :total="total"
            :page-size="pageSetting.size"
            :page-sizes="[5,10,15,20,30]"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹窗 -->
      <employeeDialog :show-dialog.sync="showDialog" @updateData="getEmployeeList" />

      <!-- 选择角色弹窗 -->
      <roleDialog ref="roleDialog" :role-dialog.sync="roleDialog" :user-id="userId" />
      <!-- 头像二维码弹窗 -->
      <el-dialog title="扫一扫查看头像" :visible.sync="codeDialog" @opened="showQRcode">
        <el-row type="flex" justify="center" align="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'

import employeesEnum from '@/api/constant/employees'

import employeeDialog from './components/employee-dialog.vue'
import roleDialog from './components/roleDialog.vue'
import { formatDate } from '@/filters/index'

// 导入生成二维码的包
import QRcode from 'qrcode'
export default {
  components: {
    employeeDialog,
    roleDialog
  },
  data() {
    return {
      showDialog: false,
      codeDialog: false,
      roleDialog: false,
      head_imgUrl: '',
      employeesList: [],
      userId: '',
      pageSetting: {
        page: 1,
        size: 5

      },
      total: 0
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageSetting)
      // 临时将第一行数据隐藏掉, 避免手滑删掉管理员
      // rows.shift()
      this.employeesList = rows
      this.total = total
      // console.log(rows, total)
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您真忍心删除该员工吗?', '提示', {
          confirmButtonText: '残忍删除',
          cancelButtonText: '回头是岸',
          type: 'warning'
        })

        await delEmployee(id)
        await this.getEmployeeList()
        this.$message.success('你好狠的心啊!')
      } catch (err) {
        console.log(err, '取消操作')
      }
    },
    // 新增弹窗
    addDialog() {
      this.showDialog = true
    },
    pageChange(currIndex) {
      this.pageSetting.page = currIndex
      this.getEmployeeList()
    },
    sizeChange(currSize) {
      this.pageSetting.size = currSize
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = employeesEnum.hireType.find(item => item.id === cellValue)
      // console.log(obj)
      return obj ? obj.value : '其他'
    },
    // 格式化时间
    formatTimeEntry(row, column, cellValue, index) {
      return cellValue.split('T')[0] || '未知'
    },
    // 导出excel文件
    async  exportData() {
      // 准备导出 excel 文件
      const excel = await import('@/vendor/Export2Excel')
      // excel.export_json_to_excel({
      //   header: tHeader, // 表头 必填
      //   data, // 具体数据 必填
      //   filename: 'excel-list', //文件名 非必填
      //   autoWidth: true, // 非必填
      //   bookType: 'xlsx' // 非必填
      // })

      const pageSetting = {
        page: 1,
        size: this.total
      }
      // 获取表格所有数据
      const { rows } = await getEmployeeList(pageSetting)
      // console.log(rows)

      // 因为表头需要中文, 但是拿数据的时候又是英文 key 所以必须
      // 做一个枚举对应
      const headersEnum = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const header = Object.keys(headersEnum)

      const data = rows.map(item => {
        return this.objToArr(item, headersEnum)
      })
      // console.log(data)

      excel.export_json_to_excel({
        header,
        data,
        filename: '员工信息表' // 文件名 非必填
      })
    },
    // 将对象转为数组
    objToArr(item, dictionary) {
      // 当前我们的 item 是对象, 里面有各种数据,
      // 应该根据枚举字典的顺序组成一个数组方便转成 excel
      const arr = []
      for (const key in dictionary) {
        const newKey = dictionary[key]
        let value = item[newKey]
        // 如果数据处理的是事件或者聘用形式, 需要额外处理
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          value = formatDate(value)
        }
        if (newKey === 'formOfEmployment') {
          const obj = employeesEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '其他'
        }
        arr.push(value)
      }
      // console.log(arr)
      return arr
    },
    // 显示二维码弹窗
    showCodeDialog(imgUrl) {
      if (imgUrl) {
        // 1. 弹出窗口
      // 2. 把当前点击的图片地址记录下来
        this.head_imgUrl = imgUrl
        this.codeDialog = true
      } else {
        this.codeDialog = false
      }
    },
    // 二维码就是将一段字符转换为二维码
    showQRcode() {
      QRcode.toCanvas(this.$refs.myCanvas, this.head_imgUrl)
    },
    async showRoleDialog(id) {
      this.userId = id
      await this.$refs.roleDialog.getRoleList()
      await this.$refs.roleDialog.getUserDetailById()
      this.roleDialog = true
    }
  }
}
</script>
<style lang="sass" scoped>

</style>
